package com.cdfahe.common.util.mail;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.ClassPathResource;

import com.cdfahe.common.util.XMLUtils;


public class MailUtils {
	public static String config = "mail-config.xml";
	public static String MAIL_CONTENT_WEL = "e://mail_content_welcome.htm";
	public static String MAIL_FILE = "file:/e://2.zip";
	public static SAXReader saxb = null;
	public static Element root = null;
	public static Document doc = null;
	public static String host = null;
	public static String port = null;
	public static String from = null;
	public static String fromname = null;
	public static String ssl = null;
	public static String username = null;
	public static String password = null;
	public static List<String> bccList = null;
	public static List<String> replyToList = null;
	public static List<String> ccList = null;
	
	public static Mail initMailServer(String filename) throws Exception {
		Mail mail = new Mail();
		saxb = new SAXReader();	
		
//		ClassPathResource c = new ClassPathResource(filename);
//		doc = XMLUtils.read(c.getFile().getPath());
		
		doc = XMLUtils.read(filename);

		root = doc.getRootElement();
		Element email = root.element("mailservers").elementByID("gmailserver");
		String rs = email.element("host").getText();
		System.out.println(rs);
		host = email.element("host").getText();
		System.out.println("邮件地址"+host);
		port = email.element("port").getText();
		from = email.element("from").getText();
		fromname = email.element("fromname").getText();
		ssl = email.element("ssl").getText();
		username = email.element("username").getText();
		password = email.element("password").getText();
		List<Element> ccElements = email.elements("cc");
		if (ccElements != null) {
			ccList = new ArrayList<String>();
			Iterator<Element> it = ccElements.iterator();
			while (it.hasNext()) {
				Element cc = it.next();
				ccList.add(cc.getText());
			}
		}

		List<Element> bccElements = email.elements("bcc");
		if (bccElements != null) {
			bccList = new ArrayList<String>();
			Iterator<Element> it = bccElements.iterator();
			while (it.hasNext()) {
				Element cc = it.next();
				bccList.add(cc.getText());
			}
		}

		List<Element> replytoElements = email.elements("replyTo");
		if (bccElements != null) {
			replyToList = new ArrayList<String>();
			Iterator<Element> it = replytoElements.iterator();
			while (it.hasNext()) {
				Element replyTo = it.next();
				replyToList.add(replyTo.getText());
			}
		}
		return mail;
	}
	
	public static void initxml(String filename) throws Exception {
		saxb = new SAXReader();	
		
		ClassPathResource c = new ClassPathResource(filename);
		doc = XMLUtils.read(c.getFile().getPath());
		
//		doc = XMLUtils.read(filename);

		root = doc.getRootElement();
		
//		Element email = root.element("mailservers").elementByID("gmailserver");
//		String rs = email.element("host").getText();
//		System.out.println(rs);
//		host = email.element("host").getText();
//		System.out.println("邮件地址"+host);
//		port = email.element("port").getText();
//		from = email.element("from").getText();
//		fromname = email.element("fromname").getText();
//		ssl = email.element("ssl").getText();
//		username = email.element("username").getText();
//		password = email.element("password").getText();
//		List<Element> ccElements = email.elements("cc");
//		if (ccElements != null) {
//			ccList = new ArrayList<String>();
//			Iterator<Element> it = ccElements.iterator();
//			while (it.hasNext()) {
//				Element cc = it.next();
//				ccList.add(cc.getText());
//			}
//		}
//
//		List<Element> bccElements = email.elements("bcc");
//		if (bccElements != null) {
//			bccList = new ArrayList<String>();
//			Iterator<Element> it = bccElements.iterator();
//			while (it.hasNext()) {
//				Element cc = it.next();
//				bccList.add(cc.getText());
//			}
//		}
//
//		List<Element> replytoElements = email.elements("replyTo");
//		if (bccElements != null) {
//			replyToList = new ArrayList<String>();
//			Iterator<Element> it = replytoElements.iterator();
//			while (it.hasNext()) {
//				Element replyTo = it.next();
//				replyToList.add(replyTo.getText());
//			}
//		}
//
	}
		
	public static String getRandomPass(){
		int pass = (int) (Math.random() * Math.pow(10, 8));
		return String.valueOf(pass);
	}
	
	public static String getSystemAddress(String configname){

		if (saxb == null | root == null | doc == null) {
			try {
				initxml(configname);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		root = doc.getRootElement();				
		Element sysadd = root.element("systemaddress");
		return sysadd.getText();


	
	}
	
	public  static void setConfigFile(String filename) {
		MailUtils.config = filename;
		if (saxb == null | root == null | doc == null) {
			try {
				initxml(filename);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		MailUtils u = new MailUtils();
		try {
			u.initxml("E://1111.xml");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
//		File file = new File("/home/roy/private/WorkTask/Eclipse_IRTS_13");
//		File ref= new File("/home/roy/Desktop/1.txt");
//		StringBuffer s = new StringBuffer();
//		File[] irtsfile = file.listFiles(new FilenameFilter() {
//			
//			@Override
//			public boolean accept(File arg0, String arg1) {
//				// TODO Auto-generated method stub
//				if (arg1.contains(".irts")){
//					return true;
//				} else {
//					return false;
//				}
//			}
//		});
//		for (File ff : irtsfile){
//		 readfile(ff,s);
//		}
//		write("/home/roy/Desktop/4.txt",s.toString());
//		getRandomPass();
	}
	
	static void readfile(File f,StringBuffer s){
		File[] ll = f.listFiles();
		for (File temp : ll){
			if (temp.isDirectory()){
				if (!temp.getName().equalsIgnoreCase("bin")&&!temp.getName().equalsIgnoreCase("workspace")&&!temp.getName().equalsIgnoreCase("resume"))
				readfile(temp,s);
			} else {
				String name = temp.getAbsolutePath();
				if (!name.contains("Entries")&&!name.contains("Root")&&!name.contains("Repository")){
					s.append(name.replace("/home/roy/private/WorkTask/Eclipse_IRTS_13/", "") +"\n");
				} 
//				System.out.println(temp.getAbsolutePath().replace("/home/roy/private/WorkTask/Eclipse_IRTS_13/", ""));
			}
		}
	}
	
	public static void write(String path, String content) {
	      String s = new String();
	      String s1 = new String();
	      try {
	       File f = new File(path);
	       if (f.exists()) {
	        System.out.println("文件存在");
	       } else {
	        System.out.println("文件不存在，正在创建...");
	        if (f.createNewFile()) {
	         System.out.println("文件创建成功！");
	        } else {
	         System.out.println("文件创建失败！");
	        }

	       }
	       BufferedReader input = new BufferedReader(new FileReader(f));

	       while ((s = input.readLine()) != null) {
	        s1 += s + "\n";
	       }
	       System.out.println("文件内容：" + s1);
	       input.close();
	       s1 += content;

	       BufferedWriter output = new BufferedWriter(new FileWriter(f));
	       output.write(s1);
	       output.close();
	      } catch (Exception e) {
	       e.printStackTrace();
	      }
	}

	
	
	/**
	 * 获取特定目标对象的邮件，并根据传入参数替换邮件模板中的变量。
	 * @param target
	 *            目标对象。
	 * @param params
	 *            需替换邮件模板变量的参数。
	 * @return Mail 构建好的邮件。
	 * @throws Exception
	 */
	public static Mail getMail(String target, Hashtable<String, String> params) throws Exception {
		Mail mail = null;
		if (saxb == null | root == null | doc == null) {
			initxml(config);
		}

		//获取邮件参数，并移除不需要参与替换的参数
		String to = params.get("TO");
		if(to != null){
			params.remove("TO");
		}
		
		String cc = params.get("CC");
		if(cc != null){
			params.remove("CC");
		}
		
		String bcc = params.get("BCC");
		if(bcc != null){
			params.remove("BCC");
		}
		
		String result = params.get("RESULT");
		if(result != null){
			params.remove("RESULT");
		}
		
		String strLanguage = params.get("LANGUAGE");
		if(strLanguage != null){
			params.remove("LANGUAGE");
		}
		
		List<Element> emts = root.elements("emt");
		Iterator<Element> it = emts.iterator();
		StringBuilder subject = new StringBuilder();
		StringBuilder content = new StringBuilder();
		while (it.hasNext()) {
			Element emt = it.next();
			if (emt.attributeValue("target").equals(target)) {
				subject.append(emt.element("subject").getText());
				content.append(emt.element("content").getText());
				break;
			}
		}

		// 无主题或内容时，直接返回空。
		if (subject.length() == 0 || content.length() == 0) {
			return null;
		}

		// 替换参数
		Iterator<String> paramIt = params.keySet().iterator();
		while (paramIt.hasNext()) {
			String key = paramIt.next();
			String value = params.get(key);
			subject = replaceParam(subject, key, value);
			content = replaceParam(content, key, value);
		}

		// 创建邮件并设置内容
		mail = new Mail(host, username, password, from);
		mail.setPort(port);
		
		if (to.contains(",")){
			String[] arrTo = to.split(",");
			for (String temp:arrTo){
				mail.addTo(temp);
			}
		} else {
			mail.addTo(to);
		}
		
		ccList.removeAll(ccList);
		mail.initializeCc(ccList);
		if(cc != null)
			mail.addCc(cc);
		bccList.removeAll(bccList);
		mail.initializeBcc(bccList);
		if(bcc != null)
			mail.addBcc(bcc);
		mail.initializeReplyto(replyToList);
		mail.setFromname(fromname);
		if (ssl.equalsIgnoreCase("true")) {
			mail.setUseSSL(true);
		} else {
			mail.setUseSSL(false);
		}
		mail.setSubject(subject.toString());
		mail.setContent(content.toString());
		return mail;
	}

	public static StringBuilder replaceParam(StringBuilder sb, String key, String value) {
		key = "***" + key + "***";
		int keySize = key.length();
		int sInx = 0; // 查找开始的位置
		int cInx = sb.indexOf(key, sInx); // 当前的位置
		while (cInx != -1) {
			sb.replace(cInx, cInx + keySize, value);
			sInx = cInx + value.length();
			cInx = sb.indexOf(key, sInx);
		}
		return sb;
	}

	public static Mail getMail(String minorNode) throws Exception {
		Mail mail = null;
		if (saxb == null | root == null | doc == null) {
			initxml(config);
		}
		
//		List<Element> grouplist = root.elements(minorNode);
//		if (grouplist != null) {
//			Element email = grouplist.get(0);
			Element email = root.elementByID(minorNode);
			String host = email.element("host").getText();
			String port = email.element("port").getText();
			String from = email.element("from").getText();
			String fromname = email.element("fromname").getText();
			String ssl = email.element("ssl").getText();
			String username = email.element("username").getText();
			String password = email.element("password").getText();
			
			String subject = email.element("subject").getText();
			String content = email.element("content").getText();
			
			List<Element> toElements = email.elements("to");
			List<String> toList = null;
			if (toElements != null) {
				toList = new ArrayList<String>();
				Iterator<Element> it = toElements.iterator();
				while (it.hasNext()) {
					Element cc = it.next();
					toList.add(cc.getText());
				}
			}

			List<Element> ccElements = email.elements("cc");
			List<String> ccList = null;
			if (ccElements != null) {
				ccList = new ArrayList<String>();
				Iterator<Element> it = ccElements.iterator();
				while (it.hasNext()) {
					Element cc = it.next();
					ccList.add(cc.getText());
				}
			}

			List<Element> bccElements = email.elements("bcc");
			List<String> bccList = null;
			if (bccElements != null) {
				bccList = new ArrayList<String>();
				Iterator<Element> it = bccElements.iterator();
				while (it.hasNext()) {
					Element cc = it.next();
					bccList.add(cc.getText());
				}
			}

			List<Element> replytoElements = email.elements("replyTo");
			List<String> replyToList = null;
			if (bccElements != null) {
				replyToList = new ArrayList<String>();
				Iterator<Element> it = replytoElements.iterator();
				while (it.hasNext()) {
					Element replyTo = it.next();
					replyToList.add(replyTo.getText());
				}
			}

			mail = new Mail(host, username, password, from);
			mail.setPort(port);
			mail.initializeTo(toList);
			mail.initializeCc(ccList);
			mail.initializeBcc(bccList);
			mail.initializeReplyto(replyToList);
			mail.setFromname(fromname);
			if (ssl.equalsIgnoreCase("true")) {
				mail.setUseSSL(true);
			} else {
				mail.setUseSSL(false);
			}
			mail.setSubject(subject);
			mail.setContent(content);
//		}
		return mail;
	}

	public static Mail getMail(String filename, String minorNode) throws Exception {
		Mail mail = null;
		config = filename;
		if (saxb == null | root == null | doc == null) {
			initxml(filename);
		}
		List<Element> grouplist = root.elements(minorNode);
		if (grouplist != null) {
			Element email = grouplist.get(0);
			String host = email.element("host").getText();
			String port = email.element("port").getText();
			String from = email.element("from").getText();
			String fromname = email.element("fromname").getText();
			String ssl = email.element("ssl").getText();
			String username = email.element("username").getText();
			String password = email.element("password").getText();
			List<Element> toElements = email.elements("to");
			List<String> toList = null;
			if (toElements != null) {
				toList = new ArrayList<String>();
				Iterator<Element> it = toElements.iterator();
				while (it.hasNext()) {
					Element cc = it.next();
					toList.add(cc.getText());
				}
			}

			List<Element> ccElements = email.elements("cc");
			List<String> ccList = null;
			if (ccElements != null) {
				ccList = new ArrayList<String>();
				Iterator<Element> it = ccElements.iterator();
				while (it.hasNext()) {
					Element cc = it.next();
					ccList.add(cc.getText());
				}
			}

			List<Element> bccElements = email.elements("bcc");
			List<String> bccList = null;
			if (bccElements != null) {
				bccList = new ArrayList<String>();
				Iterator<Element> it = bccElements.iterator();
				while (it.hasNext()) {
					Element cc = it.next();
					bccList.add(cc.getText());
				}
			}

			List<Element> replytoElements = email.elements("replyTo");
			List<String> replyToList = null;
			if (bccElements != null) {
				replyToList = new ArrayList<String>();
				Iterator<Element> it = replytoElements.iterator();
				while (it.hasNext()) {
					Element replyTo = it.next();
					replyToList.add(replyTo.getText());
				}
			}

			mail = new Mail(host, username, password, from);
			mail.setPort(port);
			mail.initializeTo(toList);
			mail.initializeCc(ccList);
			mail.initializeBcc(bccList);
			mail.initializeReplyto(replyToList);
			mail.setFromname(fromname);
			if (ssl.equalsIgnoreCase("true")) {
				mail.setUseSSL(true);
			} else {
				mail.setUseSSL(false);
			}
		}
		return mail;
	}

	public static Mail getMail() throws Exception {
		Mail mail = null;
		if (saxb == null | root == null | doc == null) {
			initxml(config);
		}
		List<Element> grouplist = root.elements("email");
		if (grouplist != null) {
			Element email = grouplist.get(0);
			String host = email.element("host").getText();
			String port = email.element("port").getText();
			String from = email.element("from").getText();
			String fromname = email.element("fromname").getText();
			String ssl = email.element("ssl").getText();
			String username = email.element("username").getText();
			String password = email.element("password").getText();
			
			String subject = email.element("subject").getText();
			String content = email.element("content").getText();
			
			List<Element> toElements = email.elements("to");
			List<String> toList = null;
			if (toElements != null) {
				toList = new ArrayList<String>();
				Iterator<Element> it = toElements.iterator();
				while (it.hasNext()) {
					Element cc = it.next();
					toList.add(cc.getText());
				}
			}

			List<Element> ccElements = email.elements("cc");
			List<String> ccList = null;
			if (ccElements != null) {
				ccList = new ArrayList<String>();
				Iterator<Element> it = ccElements.iterator();
				while (it.hasNext()) {
					Element cc = it.next();
					ccList.add(cc.getText());
				}
			}

			List<Element> bccElements = email.elements("bcc");
			List<String> bccList = null;
			if (bccElements != null) {
				bccList = new ArrayList<String>();
				Iterator<Element> it = bccElements.iterator();
				while (it.hasNext()) {
					Element cc = it.next();
					bccList.add(cc.getText());
				}
			}

			List<Element> replytoElements = email.elements("replyTo");
			List<String> replyToList = null;
			if (bccElements != null) {
				replyToList = new ArrayList<String>();
				Iterator<Element> it = replytoElements.iterator();
				while (it.hasNext()) {
					Element replyTo = it.next();
					replyToList.add(replyTo.getText());
				}
			}
			mail = new Mail(host, username, password, from);
			mail.setPort(port);
			mail.initializeTo(toList);
			mail.initializeCc(ccList);
			mail.initializeBcc(bccList);
			mail.initializeReplyto(replyToList);
			mail.setFromname(fromname);
			if (ssl.equalsIgnoreCase("true")) {
				mail.setUseSSL(true);
			} else {
				mail.setUseSSL(false);
			}
			mail.setSubject(subject);
			mail.setContent(content);
		}
		return mail;
	}

	public static List<String> getMailTo() throws Exception {
		List<String> result = new ArrayList<String>();
		if (saxb == null | root == null | doc == null) {
			initxml(config);
		}
		List<Element> grouplist = root.elements("webmaster");
		if (grouplist != null) {
			List<Element> emailList = grouplist.get(0).elements("address");
			if (emailList != null) {
				Iterator<Element> iterator = emailList.iterator();
				while (iterator.hasNext()) {
					Element email = iterator.next();
					result.add(email.getText());
				}
			}
		}
		return result;
	}

	public static String getRandomNum(int length) {
		String result = "";
		String[] array = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h",
				"i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
		for (int i = 0; i < length; i++) {
			int index = (int) (Math.random() * array.length);
			result += array[index];
		}
		return result;
	}

	public static boolean checkEmail(String stremail) {
		boolean email = false;
		String regex = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*";
		if (stremail != null && !stremail.equals("")) {
			Pattern p = Pattern.compile(regex);
			Matcher m = p.matcher(stremail);
			if (m.matches()) {
				email = true;
			} else {
				email = false;
			}
		}
		return email;
	}

	public static String toSql(String str) {
		return replace(str, "'", "\\'");
	}

	// replace the the oldString in source string to newString
	public static String replace(String source, String oldString, String newString) {
		if (source == null || oldString == null) {
			return null;
		}
		if (newString == null) {
			newString = ""; //$NON-NLS-1$
		}
		StringBuffer output = new StringBuffer();

		int lengthOfSource = source.length();// source string length
		int lengthOfOld = oldString.length();// old string length

		int posStart = 0;
		int pos;

		while ((pos = source.indexOf(oldString, posStart)) >= 0) {
			output.append(source.substring(posStart, pos));

			output.append(newString);
			posStart = pos + lengthOfOld;
		}

		if (posStart < lengthOfSource) {
			output.append(source.substring(posStart));
		}

		return output.toString();
	}

	/**
	 * 获取盘符分割符
	 * @return 盘符分割符
	 */
	public static String getFileSeparator() {
		return System.getProperty("file.separator");
	}
	
	public static String clearCDATA(String hint) {
		hint = hint.replace("<![CDATA[", "");
		return hint.replace("]]>", "");
	}
	
	public static Mail getMailForUserPassWord(String target, Hashtable<String, String> params) throws Exception {
		Mail mail = null;
		if (saxb == null | root == null | doc == null) {
			initxml(config);
		}

		//获取邮件参数，并移除不需要参与替换的参数
		String to = params.get("TO");
		if(to != null){
			params.remove("TO");
		}
		
		List<Element> emts = root.elements("emt");
		Iterator<Element> it = emts.iterator();
		StringBuilder subject = new StringBuilder();
		StringBuilder content = new StringBuilder();
		while (it.hasNext()) {
			Element emt = it.next();
			if (emt.attributeValue("target").equals(target)) {
				subject.append(emt.element("subject").getText());
				content.append(emt.element("content").getText());
				break;
			}
		}

		// 无主题或内容时，直接返回空。
		if (subject.length() == 0 || content.length() == 0) {
			return null;
		}

		// 替换参数
		Iterator<String> paramIt = params.keySet().iterator();
		while (paramIt.hasNext()) {
			String key = paramIt.next();
			String value = params.get(key);
			subject = replaceParam(subject, key, value);
			content = replaceParam(content, key, value);
		}

		// 创建邮件并设置内容
		mail = new Mail(host, username, password, from);
		mail.setPort(port);
		mail.addTo(to);
		ccList.removeAll(ccList);
		mail.initializeCc(ccList);
		bccList.removeAll(bccList);
		mail.initializeBcc(bccList);
		mail.initializeReplyto(replyToList);
		mail.setFromname(fromname);
		if (ssl.equalsIgnoreCase("true")) {
			mail.setUseSSL(true);
		} else {
			mail.setUseSSL(false);
		}
		mail.setSubject(subject.toString());
		mail.setContent(content.toString());
		return mail;
	}
	
	public static String getDownloadFolder(String configname){
		if (saxb == null | root == null | doc == null) {
			try {
				initxml(configname);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		root = doc.getRootElement();				
		Element sysadd = root.element("downloadfolder");
		return sysadd.getText();
	}
	
	public static String getIndexpath(String configname){
		if (saxb == null | root == null | doc == null) {
			try {
				initxml(configname);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		root = doc.getRootElement();				
		Element sysadd = root.element("localhostindex");
		return sysadd.getText();
	}
}